package tech.heptagram.staff.cas.controller.view;

import com.github.pagehelper.PageInfo;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import tech.heptagram.core.common.rest.ResponseResult;
import tech.heptagram.staff.cas.common.CurrentUserUtil;
import tech.heptagram.staff.cas.domain.info.RoleStaffSaveReq;
import tech.heptagram.staff.cas.domain.info.SerachStaffAndHisRoleInfo;
import tech.heptagram.staff.cas.domain.info.StaffAndHisRoleInfo;
import tech.heptagram.staff.cas.domain.po.Role;
import tech.heptagram.staff.cas.service.staff.CasRoleService;
import tech.heptagram.staff.cas.service.staff.CasStaffService;
import tech.heptagram.staff.model.Staff;
import tech.heptagram.staff.service.StaffService;

/**
 * 用户API
 *
 * @author zilaiye
 * @date 2017/12/12
 */
@RestController
@RequestMapping("/api/view/sys/user")
@Slf4j
public class CasUserApiController {
    @Resource
    private CasStaffService casStaffService;

    @Resource
    private StaffService staffService;

    @Resource
    private CasRoleService casRoleService;


    @PostMapping("/list/page")
    public ResponseResult<PageInfo<StaffAndHisRoleInfo>> findPage(@RequestBody SerachStaffAndHisRoleInfo req){

        PageInfo<StaffAndHisRoleInfo> result = new PageInfo<>();

        PageInfo<Staff> pageInfo = null;
        //如果查询的参数中不包含角色信息就直接查询staff 接口，然后获取人员角色信息
        //如果包含 则先查询角色拥有的人员信息，再获人员取角色信息
        if (Objects.isNull(req.getRole())) {
            pageInfo = staffService.findStaffsWithPage(req);
        }else {
            pageInfo = casStaffService.findRoleHasStaffPage(req.getRole(),req.getPage(), req.getPageSize());
        }

        List<StaffAndHisRoleInfo> staffAndHisRoleInfoList = new ArrayList<>(pageInfo.getList().size());
        BeanUtils.copyProperties(pageInfo,result);

        for (Staff staffResp : pageInfo.getList()) {
            StaffAndHisRoleInfo staffAndHisRoleInfo = new StaffAndHisRoleInfo();
            BeanUtils.copyProperties(staffResp, staffAndHisRoleInfo);

            List<Role> roles = casRoleService.findRolesByStaffCode(staffResp.getCode());
            staffAndHisRoleInfo.setRoles(roles);

            staffAndHisRoleInfoList.add(staffAndHisRoleInfo);
        }
        result.setList(staffAndHisRoleInfoList);

        return new ResponseResult<>(result);
    }

    @PostMapping("/setRoles")
    public ResponseResult<Integer> saveStaffRole(@RequestBody RoleStaffSaveReq req){
        req.setCreatedBy(CurrentUserUtil.getCurrentUser().getTrueName());
        Integer nums = casStaffService.saveRoleStaffRelation(req);
        return new ResponseResult<>(nums);
    }
}
